package com.citycloud.ccuap.tc.admin.datagroup;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.citycloud.ccuap.commons.constants.GlobalOperateType;
import com.citycloud.ccuap.commons.sys.entity.SysGroup;
import com.citycloud.ccuap.commons.sys.entity.SysRole;
import com.citycloud.ccuap.commons.sys.repository.SysGroupRepository;
import com.citycloud.ccuap.commons.sys.repository.SysProjectRepository;
import com.citycloud.ccuap.commons.sys.repository.SysRoleRepository;
import com.citycloud.ccuap.commons.web.session.CurrentUser;
import com.citycloud.ccuap.framework.service.mybatis.MybatisServiceImpl;
import com.citycloud.ccuap.framework.util.StringUtil;
import com.citycloud.ccuap.tc.admin.entity.SysDatagroup;
import com.citycloud.ccuap.tc.admin.entity.SysDatagroupLevel;
import com.citycloud.ccuap.tc.admin.repository.SysDatagroupLevelRepository;
import com.citycloud.ccuap.tc.admin.repository.SysDatagroupRepository;
import com.citycloud.ccuap.tc.yq.dto.CheckedTreeNodeDTO;
import com.citycloud.ccuap.tc.yq.entity.SysDimensionBustype;
import com.citycloud.ccuap.tc.yq.entity.SysDimensionCls;
import com.citycloud.ccuap.tc.yq.entity.SysDimensionDs;
import com.citycloud.ccuap.tc.yq.entity.SysDimensionField;
import com.citycloud.ccuap.tc.yq.entity.SysDimensionTable;
import com.citycloud.ccuap.tc.yq.entity.SysDimensionTableConfig;
import com.citycloud.ccuap.tc.yq.metafield.MetaFieldMapper;
import com.citycloud.ccuap.tc.yq.repository.MetaFieldRepository;
import com.citycloud.ccuap.tc.yq.repository.SysDimensionBustypeRepository;
import com.citycloud.ccuap.tc.yq.repository.SysDimensionClsRepository;
import com.citycloud.ccuap.tc.yq.repository.SysDimensionDsRepository;
import com.citycloud.ccuap.tc.yq.repository.SysDimensionFieldRepository;
import com.citycloud.ccuap.tc.yq.repository.SysDimensionTableConfigRepository;
import com.citycloud.ccuap.tc.yq.repository.SysDimensionTableRepository;

/**
 * 数据组业务处理实现
 * @author sufeng
 *
 */
@Service
public class DatagroupService extends MybatisServiceImpl<SysDatagroupRepository, SysDatagroup, String> implements IDatagroupService {
	@Autowired
    private SysRoleRepository sysRoleRepository;

	@Autowired
    private SysProjectRepository sysProjectRepository;
	
    @Autowired
    private SysDatagroupRepository sysDatagroupRepository;

    @Autowired
    MetaFieldRepository metaFieldRepository;

    @Autowired
    private SysDimensionClsRepository secDimensionClsRepository;

    @Autowired
    private SysDimensionTableRepository secDimensionTableRepository;

    @Autowired
    private SysDimensionFieldRepository secDimensionFieldRepository;

    @Autowired
    private SysDimensionTableConfigRepository secDimensionTableConfigRepository;

//    @Autowired
//    private SysDimensionFieldConfigRepository secDimensionFieldConfigRepository;
    
    
    @Autowired
    private SysDimensionDsRepository secDimensionDsRepository;

    @Autowired
    private SysDatagroupLevelRepository sysDatagroupLevelRepository;

    @Autowired
    private SysDimensionBustypeRepository secDimensionBustypeRepository;

    @Autowired
    private SysGroupRepository sysGroupRepository;
    
    @Autowired
    @Lazy
    private DataGroupMapper dataGroupMapper;

    @Autowired
    @Lazy
    private MetaFieldMapper metaFieldMapper;
    
    @Override
    public List<SysRole> findSysRoleByDatagroupId(String datagroupId) {
        return dataGroupMapper.findSysRoleByDatagroupId(datagroupId);
    }

    @Override
    @CacheEvict(cacheNames="datagroupCache", key = "#sysDatagroupAllDTO.sysDatagroup.datagroupId")
    public void save(SysDatagroupAllDTO sysDatagroupAllDTO, CurrentUser currentUser) {
        SysDatagroup sysDatagroup = null;
        if (GlobalOperateType.ADD == sysDatagroupAllDTO.getOperateType()) {
            sysDatagroup = sysDatagroupAllDTO.getSysDatagroup();
            sysDatagroup.setCreator(currentUser.getUser().getUserNo());
            sysDatagroup.setCreatedTime(new Date());
            sysDatagroup.setDatagroupId(null);
            sysDatagroup = sysDatagroupRepository.save(sysDatagroup);
        } else if (GlobalOperateType.EDIT == sysDatagroupAllDTO.getOperateType()) {
        	sysDatagroupAllDTO.getSysDatagroup().setUpdator(currentUser.getUser().getUserNo());
        	sysDatagroupAllDTO.getSysDatagroup().setUpdatedTime(new Date());
            sysDatagroup = sysDatagroupRepository.update(sysDatagroupAllDTO.getSysDatagroup());
            sysDatagroupLevelRepository.deleteByDatagroupId(sysDatagroup.getDatagroupId());
            secDimensionClsRepository.deleteByDatagroupId(sysDatagroup.getDatagroupId());
            secDimensionTableRepository.deleteByDatagroupId(sysDatagroup.getDatagroupId());
            secDimensionFieldRepository.deleteByDatagroupId(sysDatagroup.getDatagroupId());
            secDimensionBustypeRepository.deleteByDatagroupId(sysDatagroup.getDatagroupId());
            secDimensionDsRepository.deleteByDatagroupId(sysDatagroup.getDatagroupId());
        }


        if(null != sysDatagroupAllDTO.getLevels()){
            for (Long item : sysDatagroupAllDTO.getLevels()) {
                SysDatagroupLevel datagroupLevel = new SysDatagroupLevel();
                datagroupLevel.setDatagroupId(sysDatagroup.getDatagroupId());
                datagroupLevel.setLevelId(item);
                sysDatagroupLevelRepository.save(datagroupLevel);
            }
        }

        if(null != sysDatagroupAllDTO.getDimensionDsId()){
            for (String item : sysDatagroupAllDTO.getDimensionDsId()) {
                SysDimensionDs sysDimensionDs = new SysDimensionDs();
                sysDimensionDs.setDatagroupId(sysDatagroup.getDatagroupId());
                sysDimensionDs.setDsId(item);
                secDimensionDsRepository.save(sysDimensionDs);
            }
        }

        if(null != sysDatagroupAllDTO.getDimensionCateId()){
            for (String item : sysDatagroupAllDTO.getDimensionCateId()) {
                SysDimensionCls secDimensionCls = new SysDimensionCls();
                secDimensionCls.setDatagroupId(sysDatagroup.getDatagroupId());
                secDimensionCls.setCateId(item);
                secDimensionClsRepository.save(secDimensionCls);
            }
        }


        if(null != sysDatagroupAllDTO.getDimensionTableId()){
            for (String item : sysDatagroupAllDTO.getDimensionTableId()) {
                SysDimensionTable secDimensionTable = new SysDimensionTable();
                secDimensionTable.setDatagroupId(sysDatagroup.getDatagroupId());
                secDimensionTable.setTableId(item);
                secDimensionTableRepository.save(secDimensionTable);
            }
        }

        for (String item : sysDatagroupAllDTO.getDimensionFieldId()) {
            SysDimensionField secDimensionField = new SysDimensionField();
            secDimensionField.setDatagroupId(sysDatagroup.getDatagroupId());
            secDimensionField.setFieldId(item);
            secDimensionFieldRepository.save(secDimensionField);
        }

        for(SysDimensionBustype secDimensionBustype:sysDatagroupAllDTO.getDimensionBuseTypes()){
            secDimensionBustype.setDatagroupId(sysDatagroup.getDatagroupId());
            secDimensionBustypeRepository.save(secDimensionBustype);
        }
    }

    @Override
    public List<CheckedTreeNodeDTO> findBusiNextChildNodeTree(List<String> list,Long pid, Integer dataStatus) {
        List<CheckedTreeNodeDTO> treeList = new ArrayList<CheckedTreeNodeDTO>();

        List<SysGroup> nodeList;
        if (pid == null) {
            if (dataStatus == null) {
                nodeList = sysGroupRepository.findByPidNullOrderByOrderNo();
            } else {
                nodeList = sysGroupRepository.findByPidNullAndDataStatusOrderByOrderNo(dataStatus);
            }
        } else {
            if (dataStatus == null) {
                nodeList = sysGroupRepository.findByPidOrderByOrderNo(pid);
            } else {
                nodeList = sysGroupRepository.findByPidAndDataStatusOrderByOrderNo(pid, dataStatus);
            }
        }
        if (nodeList != null) {
            for (SysGroup sysGroup : nodeList) {
                CheckedTreeNodeDTO node = new CheckedTreeNodeDTO();
                node.setId(sysGroup.getGroupId().toString());
                node.setText(sysGroup.getGroupName());
                node.setExpanded(true);
                boolean isLeaf = !hasChildNode(sysGroup.getGroupId(), dataStatus);
                node.setLeaf(isLeaf);
                node.setGroupNo(sysGroup.getGroupNo());
                if(sysGroup.getPid()!=null) {
                	node.setParentNode(sysGroup.getPid().toString());
                }else {
                	node.setParentNode(null);
                }
                if(!isLeaf){
                    node.setChildrenModel(findBusiNextChildNodeTree(list,sysGroup.getGroupId(),1));
                }
                if(list.contains(node.getId())){
                    node.setChecked(true);
                }else{
                    node.setChecked(false);
                }
                treeList.add(node);
            }
        }

        return treeList;
    }

    @Override
    public List<SysDatagroup> findDataGroupByRoleId(Long roleId,Long projectId) {
        return dataGroupMapper.findDataGroupByRoleId(roleId,projectId);
    }

    private boolean hasChildNode(Long pid, Integer dataStatus) {
        Long count = null;
        if (dataStatus == null) {
            count = sysGroupRepository.countByPid(pid);
        } else {
            count = sysGroupRepository.countByPidAndDataStatus(pid, dataStatus);
        }

        if (count == 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取所有数据组
     */
	@Override
	public List<SysDatagroup> getAllList(String userId, String projectId) {
		return dataGroupMapper.getAllList( userId,  projectId);
	}

	@Override
	@CacheEvict(cacheNames="datagroupCache", key = "#datagroupId")
	public void deleteByObjId(String datagroupId) {
		if ("".equals(datagroupId)) {
			return;
		}

		deleteById(datagroupId);
//		sysDatagroupLevelRepository.deleteByDatagroupId(datagroupId);
//        secDimensionClsRepository.deleteByDatagroupId(datagroupId);
        secDimensionTableConfigRepository.deleteByDatagroupId(datagroupId);
//        secDimensionFieldConfigRepository.deleteByDatagroupId(datagroupId);
        secDimensionBustypeRepository.deleteByDatagroupId(datagroupId);
	}

	@Override
	public void deleteObjIdList(List<String> objIdList) {
		for(int i=0;i<objIdList.size();i++) {
			deleteByObjId(objIdList.get(i));
		}
	}

	@Override
	public void saveCondition(SysDimensionBustype dimensionBuseTypes) {
            secDimensionBustypeRepository.save(dimensionBuseTypes);
	}

	@Override
	public void addTableConfig(String datagroupId,List<SysDimensionTableConfigDTO> configList) {
		for(int i=0;i<configList.size();i++) {
			SysDimensionTableConfigDTO dto=configList.get(i);
			SysDimensionTableConfig config=new SysDimensionTableConfig();
			config.setDatagroupId(datagroupId);
			config.setDsId(dto.getDsId());
			config.setFirstCatId(dto.getFirstCatId());
			config.setSecondCatId(dto.getSecondCatId());
            config.setFieldEnames(dto.getFields());
			config.setTableId(dto.getTableId());
			if(StringUtils.isNotBlank(dto.getFields())){
                String fieldcnames = metaFieldMapper.getFieldCnameByTableIdAndFieldEnames(dto.getTableId(),Arrays.asList(dto.getFields().split(",")));
                config.setFieldCnames(fieldcnames);
                
            } else {
                config.setFieldCnames(null);
            }
			secDimensionTableConfigRepository.save(config);
		}
		
	}

	@Override
	public void addFieldConfig(String datagroupId, String tableConfigId, String fields) {
        SysDimensionTableConfig config = secDimensionTableConfigRepository.findById(tableConfigId).get();
        config.setFieldEnames(fields);
        if(StringUtils.isNotBlank(fields)){
            String fieldcnames = metaFieldMapper.getFieldCnameByTableIdAndFieldEnames(config.getTableId(),Arrays.asList(fields.split(",")));
            config.setFieldCnames(fieldcnames);
            
        }
        secDimensionTableConfigRepository.save(config);
	}

	@Override
	public void deleteTable(String tableConfigIds) {
		List<String> tableList=StringUtil.strToStringList(tableConfigIds);
		for(int i=0;i<tableList.size();i++) {
			secDimensionTableConfigRepository.deleteById(tableList.get(i));
		}
	}

	@Override
	public void deleteBusType(String objId) {
		secDimensionBustypeRepository.deleteById(objId);
	}

    /**
     * 获取当前角色下的所有数据组
     * @param roleId
     * @return
     */
    @Override
    public List<SysDatagroup> getByRoleId(Long roleId) {

        return dataGroupMapper.getByRoleId(roleId);
    }
}